﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Polly;
using Polly.Extensions.Http;
using SageKing.Core.Abstractions;

namespace SageKing.APIGateway.Yarp.Options;

public class PollyfiedClientOptions : IOptionsBase
{
    public string SectionName => "PollyfiedClientOptions";

    /// <summary>
    /// 重试策略 - 重试次数
    /// sleepDurationProvider: Math.Pow(2, retryAttempt) * 100
    /// </summary>
    public int RetryCount { get; set; } = 3;

    /// <summary>
    /// 熔断器策略 - 连续失败阈值
    /// 请求连续失败超过此数值时触发熔断
    /// </summary>
    public int AllowedBeforeBreaking { get; set; } = 5;

    /// <summary>
    /// 熔断器策略 - 熔断持续时间（秒）
    /// 在接下来的指定秒数内，所有发往该服务的请求会立即被拒绝
    /// </summary>
    public int DurationOfBreak { get; set; } = 30;

    // 超时策略（可选）
    public int TimeoutSeconds { get; set; } = 30;

    // 高级熔断器配置（可选）
    public double FailureThreshold { get; set; } = 0.5;
    public int SamplingDurationSeconds { get; set; } = 10;
    public int MinimumThroughput { get; set; } = 5;




    // 对应的策略工厂扩展
    public static IAsyncPolicy<HttpResponseMessage> CreateAdvancedCircuitBreakerPolicy(PollyfiedClientOptions options)
    {
        return HttpPolicyExtensions
            .HandleTransientHttpError()
            .AdvancedCircuitBreakerAsync(
                failureThreshold: options.FailureThreshold,
                samplingDuration: TimeSpan.FromSeconds(options.SamplingDurationSeconds),
                minimumThroughput: options.MinimumThroughput,
                durationOfBreak: TimeSpan.FromSeconds(options.DurationOfBreak)
            );
    }
}